import {IComponentType} from "@bastet/widgets";
import type {IComponent} from "@bastet/widgets";
import { widgets as testWidgetNames } from '../../widgets.json';

const fetchWidget = (path: string) => fetch(path).then(res => res.text())
const localWidgetObject: Map<string, Promise<any>> = (import.meta as any).glob('/src/widget/**/index.tsx');

export interface IWidgetRemote {
  id: string;
  version: string;
  name: string;
  type: string;
  renderProps: any;
  path: string; // "widgets/card.0.0.1.js"
  children: any[];
}

export function resizeCustom(settings: IComponent = {} as any) {
  const { name, config, renderProps }= settings;
  if (!settings.children) settings.children = []
  switch (name?.toLowerCase()) {
    case 'grid': {
      if (config) {
        const { column = 1, row = 1, type } = config
        if (type === 'WIDGET:GRID') {
          const gridRow = new Array(row).fill(null)
          const gridColumn = new Array(column).fill(null)
          // console.log('children', settings.children)
          settings.children = gridRow.map((_, row) => {
            return {
              name: `GRID-ROW`,
              type: IComponentType.DRAG,
              renderProps: { className: 'row ' },
              children: gridColumn.map((_, col) => {
                const children = settings.children?.[row]?.children?.[col]?.children || []
                // console.log('children', children)
                return {
                  name: 'GRID-COLUMN',
                  type: IComponentType.DROP,
                  renderProps: { className: `col-${24 / column} ` },
                  children
                }
              })
            }
          })
        }
      }
    }
  }
}

/**
 * 加载本地组件
 */
export async function loadLocalWidgets () {
  const localWidgetMap = new Map()

  for (let [path, localWidget] of Object.entries(localWidgetObject)) {
    const widget = await localWidget();
    if (widget) {
      path = path.replace('/index.tsx', '')
      const widgetName = path.split('/').pop()
      const upperCaseName = widgetName!.toLocaleUpperCase();
      widget.settings.name = upperCaseName;
      resizeCustom(widget.settings)
      localWidgetMap.set(upperCaseName, widget)
      // console.log('widgets: => ', upperCaseName, widget)
    }
  }

  // console.log('localWidgetMap: => ', localWidgetMap)
  return localWidgetMap;
}

/**
 * 当前场景中用到的所有组件
 *
 * @param widgetData
 */
export async function loadRemoteWidgets(widgetData: IWidgetRemote[]) {
  const remoteWidgetMap: Map<string, any> = new Map()
  return Promise.all(
    widgetData
      .map(widget => fetchWidget(`/${widget.path}`)
        .then(componentText => {
          // 获取组件名称
          const nameLowerCase = widget.name.toLocaleLowerCase()
          // 执行组件
          eval(componentText)

          const remoteWidget = (window as any)[`$${nameLowerCase}`];
          remoteWidget.settings.name = widget.name;
          remoteWidgetMap.set(widget.name, remoteWidget);
          delete (window as any)[`$${nameLowerCase}`]
          return { name: nameLowerCase, componentText }
        }))
  ).then(() => remoteWidgetMap)
}
